var sidebarGui = {
  addAttribute : function(attrName, attrValue){
    var attributeChilds = document.getElementById('attributeChilds');
    var item = document.createElement('treeitem');
    var row = document.createElement('treerow');
    var c1 = document.createElement('treecell');
    var c2 = document.createElement('treecell');
    c1.setAttribute('label', attrName);
    c2.setAttribute('label', attrValue);
    row.appendChild(c1);
    row.appendChild(c2);
    item.appendChild(row);
    attributeChilds.appendChild(item);
  },

  clearAttributes : function(){
    var attributeChilds = document.getElementById('attributeChilds');
    while (attributeChilds.hasChildNodes()) attributeChilds.removeChild(attributeChilds.firstChild);
  },

  addResource : function(resName, resHref){
    var resourceList = document.getElementById('resourceList');
    var item = document.createElement('listitem');
    item.setAttribute('label', resName);
    item.setAttribute('value', resHref);
    resourceList.appendChild(item);
  },

  clearResources : function(){
    var resourceList = document.getElementById('resourceList');
    while (resourceList.hasChildNodes()) resourceList.removeChild(resourceList.firstChild);
  },

  showViewpoints_addViewpoint : function(vpName, vpHref){
    var viewpointList = document.getElementById('viewpointList');
    var items = viewpointList.getElementsByTagName('listitem');
    for(var i=0; i < items.length; i++){
      var item = items[i];
      var vpUrl = item.getAttribute("value");
      if(vpUrl.length > 0 && vpUrl == vpHref)
        return;
    }
    var item = document.createElement('listitem');
    item.setAttribute('label', vpName);
    item.setAttribute('value', vpHref);
    viewpointList.appendChild(item);
  },

  /**
   * Show fragments in the selected viewpoint's panel
   */
  showFragmentsInViewpoints: function(fragments){

    var viewpointUri = this.getSelectedPanelViewpointUri();
    if(viewpointUri == null) return;


    debug("[sidebarGui.js::showFragmentsInViewpoints] viewpointUri:" + viewpointUri, 4);
    var panels = document.getElementsByTagName('tabpanel');
    for(var i = 0;i < panels.length; i++){
      var panel = panels[i];
      if(!panel.hasAttribute("href") || panel.getAttribute("href") != viewpointUri)
        continue;
      var viewpointHref = panel.getAttribute("href");
      debug("[sidebarGui.js::showFragmentsInViewpoints] panel:" + viewpointHref,3);
      var fragmentContainer = null;
      try{
        fragmentContainer = document.getElementById('fragment_' + MD5(viewpointHref));
      }catch(ex) { break; }
      this.clearFragmentLabel(fragmentContainer);
      if(fragments == null) return;
      var_dump("[sidebarGui.js::showFragmentsInViewpoints] fragment numbers:", fragments,3);
      for(m = 0; m < fragments.length; m++){
    		var f = fragments[m];
    		if(f.viewpoints == null) continue;
    		for(var j=0; j < f.viewpoints.length; j++){
    		  debug("[sidebarGui.js::showFragmentsInViewpoints] viewpoint uri:" + f.viewpoints[j],3);
    		  if(f.viewpoints[j] == viewpointHref){
    		    var el = this.createFragmentLabel(f);
    		    fragmentContainer.appendChild(el);
    		  }
    		}
      }
    }
  },

	createFragmentLabel: function(fragment){
  	var stringBundle = document.getElementById("sbLasuli");
    debug("[lasuliSidebar.js::creatFragmentLabel] fragment:" + dump(fragment), 3);
		var labelElement = document.createElement('label');
		labelElement.appendChild(document.createTextNode(fragment.content));
		labelElement.setAttribute("context", "popupFragment");
		labelElement.setAttribute("style", "background-color:" + COLORS[fragment.colorIndex] + ";");
		labelElement.setAttribute("class", "roundedLabel");
		labelElement.setAttribute("id", "fragment_" + fragment.startPos + "_" + fragment.endPos);
		labelElement.setAttribute("fragment", fragment.toJSONString());
		labelElement.setAttribute("onmouseover", "sidebar.bgTags(this)");
		labelElement.setAttribute("onmouseout", "sidebar.bgOffTags()");
		return labelElement;
  },

  clearFragmentLabel: function(fragmentContainer){
		while (fragmentContainer.firstChild) {
  		fragmentContainer.removeChild(fragmentContainer.firstChild);
		}
	},

  clearViewpoints : function(){
    var viewpointList = document.getElementById('viewpointList');
    while (viewpointList.hasChildNodes()) viewpointList.removeChild(viewpointList.firstChild);
  },

  clearTagCloud: function(){
    var uri = this.getSelectedPanelViewpointUri();
    if(uri == null)	return;
    var tagCloudBox = document.getElementById('tagcloud_' + MD5(uri));
    while (tagCloudBox.hasChildNodes()) tagCloudBox.removeChild(tagCloudBox.firstChild);
  },

  openResourceUrl: function(resourceUrl){
    if((typeof resourceUrl)!= "string" || !resourceUrl.isUrl())
      return;

    var browserEnumerator = windowMediator.getEnumerator("navigator:browser");
    var browserInstance = browserEnumerator.getNext().getBrowser();

    // Create tab
    var newTab = browserInstance.addTab(resourceUrl);

    // Focus tab
    browserInstance.selectedTab = newTab;
    browserInstance.focus();
  },

  doOpenViewpointTabPanel: function(name, href){
    var tabPanelsParent = document.getElementById("LaSuli_Sidebar_TabPanel");
    var tabsParent = document.getElementById("LaSuli_Sidebar_Tab");
    var tabPanels = document.getElementsByTagName("tabpanel");
    for (var i = 0; i < tabPanels.length; i++) {
      var uriOfTab = tabPanels[i].getAttribute("href");
      if(uriOfTab == href){
        debug("[lasuliSidebar.js::openViewpointTabPanel] tabPanel already opened!" ,2 );
        return;
      }
    }

    debug("[lasuliSidebar.js::openViewpointTabPanel] tabPanelsParent id:" + tabPanelsParent.getAttribute("id") ,2 );
    var tab = document.createElement('tab');
    var label = document.createElement('label');
    //var toolbarbutton = document.createElement('toolbarbutton');
    tab.setAttribute('href', href);
    tab.setAttribute('linkedpanel', 'tabpanel_' + MD5(href));
    //toolbarbutton.setAttribute('href', href);
    //toolbarbutton.addEventListener('click', sidebar.doCloseViewpointTabPanel,false);

    label.setAttribute('value', name);
    tab.appendChild(label);

    tabsParent.appendChild(tab);
//    tabsParent.appendChild(toolbarbutton);

    var tabPanel = document.createElement('tabpanel');
    tabPanel.setAttribute('href', href);
    tabPanel.setAttribute('id', 'tabpanel_' + MD5(href));
    tabPanelsParent.appendChild(tabPanel);

    var vboxContainer = document.createElement('vbox');
    vboxContainer.setAttribute('flex', '1');
    tabPanel.appendChild(vboxContainer);

    var vbox = document.createElement('vbox');
    vbox.setAttribute('href', href);
    vbox.setAttribute('id', 'tagcloud_' + MD5(href));
    //vbox.setAttribute('flex', '1');
    vbox.setAttribute('style', 'overflow: none');
    vboxContainer.appendChild(vbox);

    /*var splitter = document.createElement('splitter');
    splitter.setAttribute('collapse', 'after');
    splitter.setAttribute('resizebefore', 'closest');
    splitter.setAttribute('resizeafter', 'closest');
    vboxContainer.appendChild(splitter);

    var grippy = document.createElement('grippy');
    splitter.appendChild(grippy);*/

    vbox = document.createElement('vbox');
    vbox.setAttribute('href', href);
    vbox.setAttribute('id', 'fragment_' + MD5(href));
    vbox.setAttribute('flex', '1');
    vbox.setAttribute('style', 'overflow: auto');
    vboxContainer.appendChild(vbox);
  },

  getSelectedPanelViewpointUri: function(){
    var tabPanelsParent = document.getElementById("LaSuli_Sidebar_TabPanel");
    var viewpointUri = null;
    debug("[sidebarGui.js::getSelectedPanelViewpointUri] tabPanelsParent.selectedIndex" + tabPanelsParent.selectedIndex, 1);
    if(tabPanelsParent.selectedIndex > 0 && tabPanelsParent.selectedPanel.hasAttribute("href"))
        viewpointUri = tabPanelsParent.selectedPanel.getAttribute("href");
    return viewpointUri;
  }
}

var jsContextMenu = {
  selectedTag:null,

  getPopupSource:function(){
    var node = document.popupNode;
    if(node.hasAttribute("uri")){
      debug("[lasuliSidebar.js::getPopupSource] popup source:" + node.getAttribute("uri"), 3);
      this.selectedTag = node;
      return;
    }
    this.selectedTag = null;
  },

  getPopupFragmentSource:function(){
    var node = document.popupNode;

    if(node.hasAttribute("fragment")){
      sidebar.selectedFragment = node.getAttribute("fragment");
      debug("[lasuliSidebar.js::getPopupSource] node:" + node.getAttribute("fragment"), 4);
      return;
    }
    sidebar.selectedFragment = null;
  },

  doContextMenuRenameTag: function(){
    debug("[lasuliSidebar.js::doContextMenuRenameTag] selectedTag:" + this.selectedTag.getAttribute("uri"), 3);
    debug("[lasuliSidebar.js::doContextMenuRenameTag] selectedTag:" + this.selectedTag.firstChild.nodeValue, 3);
    if(this.selectedTag == null) return false;
    var retVals = { uri : this.selectedTag.getAttribute("uri"), name: this.selectedTag.firstChild.nodeValue, newName: null};
    openDialog("chrome://lasuli/content/topicDialog.xul", "dlg-topic", "modal", retVals);
    if(retVals.newName != null){
      this.selectedTag.firstChild.nodeValue = retVals.newName;
    }
  },

  doContextMenuOpenTopicInPorphyry: function(){
    debug("[lasuliSidebar.js::doContextMenuOpenTopicInPorphyry] selectedTag:" + this.selectedTag.getAttribute("uri"), 3);
    if(this.selectedTag == null) return false;
      window.open(PORPHYRY_PREFIX + this.selectedTag.getAttribute("uri"));
  },

  doContextMenuOpenPorphyry : function(){
  	var stringBundle = document.getElementById("sbLasuli");
    var viewpointList = document.getElementById("viewpointList");
    if(viewpointList.selectedItem == null){
      alert(stringBundle.getString("sidebar.info.selectavp"));
      return false;
    }
    window.open(PORPHYRY_PREFIX + viewpointList.selectedItem.value);
  },

  doContextMenuOpenViewpoint : function(){
  	var stringBundle = document.getElementById("sbLasuli");
    var viewpointList = document.getElementById("viewpointList");
    if(viewpointList.selectedItem == null){
    	alert(stringBundle.getString("sidebar.info.selectavp"));
      return false;
    }
    sidebarGui.doOpenViewpointTabPanel(viewpointList.selectedItem.label, viewpointList.selectedItem.value);
  },

  doContextMenuAddFragment: function(colorIndex){
    //alert(colorIndex);
    var fragment = jsSelection.getSelectionPos();
    fragment.colorIndex = colorIndex;
    var viewpointUri = sidebarGui.getSelectedPanelViewpointUri();
    debug("[sidebarGui.js:doContextMenuAddFragment] viewpointUri:" + viewpointUri,4);
    jsFragments.addFragment(fragment, viewpointUri);
    sidebar.showHighLighter(true);
  },

  doTest: function(){

    var source = "<html><body>hello world!</body></html>";
    if(sidebar.docHtml != "")
      source = sidebar.docHtml;
    var doc = mainWindow.getBrowser().contentDocument.wrappedJSObject;
    doc.open("text/html", "replace");
    doc.write(source);
    doc.close();

    //debug("[sidebarGui.js::doTest]" + doc.innerHTML,4);
  }
}